package com.liangzhong.proxy.login
{
	import com.adobe.serialization.json.JSON;
	import com.common.stdlib.StringUtil;
	import com.liangzhong.commandconst.activity.CMD_Activity;
	import com.liangzhong.commandconst.commandType.MainCommandType;
	import com.liangzhong.commandconst.logic.CMD_Logic;
	import com.liangzhong.commandconst.login.CMD_Login;
	import com.liangzhong.commandconst.stadium.CMD_Stadium;
	import com.liangzhong.constants.ApplicationConstants;
	import com.liangzhong.constants.HttpRequestConst;
	import com.liangzhong.errortip.ErrorTips;
	import com.liangzhong.global.CMD_Head;
	import com.liangzhong.global.TGW_Head;
	import com.liangzhong.model.AppData;
	import com.liangzhong.model.guide.vo.GuideSettingVo;
	import com.liangzhong.model.login.LoginAwardVo;
	import com.liangzhong.model.login.SignInfoVo;
	import com.liangzhong.proxy.BaseProxy;
	import com.liangzhong.proxy.ProxyUtils;
	import com.liangzhong.proxy.club.ClubProxy;
	import com.liangzhong.proxy.training.TrainingProxy;
	import com.socket.clientsocket.IClientSocket;
	import com.socket.clientsocket.IClientSocketHandler;
	
	import flash.events.Event;
	import flash.net.URLVariables;
	import flash.utils.ByteArray;
	
	import lz.controls.Alert;
	
	public class LoginProxy extends BaseProxy implements IClientSocketHandler
	{
		public static const ProxyName :String = "LoginProxy";
		/**
		 *登录返回 
		 */		
		public static const Login_Result :String = "Server/login/Login_Result";
		/**
		 * 名字验证返回
		 */		
		public static const CheckUp_Name_Result :String = "Server/login/CheckUp_Name_Result";
		/**
		 *登录奖励信息 返回 
		 */		
		public static const Login_LoginAwardInfo_Result :String = "Server/login/Login_LoginAwardInfo_Result";
		/**
		 *获取登录奖励 返回 
		 */		
		public static const Login_GetLoginAward_Result	  :String = "Server/login/Login_GetLoginAward_Result";
		/**
		 *错误对象 
		 */		
		private var errorObj :Object = {101:"服务器忙",102:"俱乐部名字为空",103:"俱乐部名字已经被使用",104:"头像错误",105:"国家错误",106:"位置错误"};
		
		public function LoginProxy(proxyName:String = ProxyName, data:Object=null)
		{
			super(proxyName, data);
		}
		/**
		 * 数据读取
		 * @param mainCmdID
		 * @param subCmdID
		 * @param buffer
		 * @param dataSize
		 * @param clientSocket
		 * @return 
		 */		
		override public function onSocketRead(mainCmdID:uint,
											  subCmdID:uint,
											  buffer:ByteArray, 
											  dataSize:int, 
											  clientSocket:IClientSocket):Boolean
		{
			switch(mainCmdID)
			{
				case CMD_Login.MAIN:
				case CMD_Logic.MAIN:
				{
					return onDealLogin(mainCmdID,subCmdID,buffer,dataSize);
				}
				case MainCommandType.TASK:
				{
					return onDealTask(mainCmdID,subCmdID,buffer,dataSize);
				}
			}
			return false;
		}
		
		/**
		 * 处理信息
		 * @param mainCmdID
		 * @param subCmdID
		 * @param buffer
		 * @param dataSize
		 * @return 
		 * 
		 */		
		private function onDealTask(mainCmdID:uint,
									 subCmdID:uint,
									 buffer:ByteArray, 
									 dataSize:int):Boolean
		{
			var retCode :int;
			var signInfoVo :SignInfoVo;
			switch(subCmdID)
			{
				case CMD_Login.SUB_SIGN://签到
				{
					retCode = buffer.readInt();
					if(retCode == 0)
					{
						var ntype :int = buffer.readByte();
						var cashpoint :int = buffer.readInt();
						var day		:int = buffer.readByte();
						var dayTags :Array;
						if(ntype == 1)//签到
						{
							signInfoVo = AppData.getInstance().user.signInfoVo;
							signInfoVo.is_sign = 1;
							signInfoVo.is_get_today = 2;
							dayTags = signInfoVo.signDayTags;
							dayTags[dayTags.length - 1] = 1;
							signInfoVo.continue_sign ++;
							signInfoVo.sign_days ++;
							if(signInfoVo.sign_days == 5)
							{
								signInfoVo.getDayFlags[0] = 2;
							}
							else if(signInfoVo.sign_days == 12)
							{
								signInfoVo.getDayFlags[1] = 2;
							}
							else if(signInfoVo.sign_days == 26)
							{
								signInfoVo.getDayFlags[2] = 2;
							}
						}
						else if(ntype == 2)//补签
						{
							signInfoVo  = AppData.getInstance().user.signInfoVo;
							dayTags = signInfoVo.signDayTags;
							signInfoVo.reSignDays ++;
							signInfoVo.sign_days ++;
							var wDay :int = day;//第几天
							dayTags[wDay - 1] = 1;
							if(signInfoVo.sign_days == 5)
							{
								signInfoVo.getDayFlags[0] = 2;
							}
							else if(signInfoVo.sign_days == 12)
							{
								signInfoVo.getDayFlags[1] = 2;
							}
							else if(signInfoVo.sign_days == 26)
							{
								signInfoVo.getDayFlags[2] = 2;
							}
						}
						AppData.getInstance().user.signInfoVo.dispatchEvent(new Event(Event.CHANGE));
					}
					else
					{
						Alert.showErrorTip(ErrorTips.instance.getCErrorTip(retCode) + "");
					}
					return true;
				}
				case CMD_Login.SUB_SIGN_AWARD://签到奖励
				{
					retCode = buffer.readInt();
					if(retCode == 0)
					{
						Alert.showErrorTip("领取奖励成功");
						var type :int = buffer.readByte();
						signInfoVo = AppData.getInstance().user.signInfoVo;
						if(type == 1)
						{
							signInfoVo.is_get_today = 1;
						}
						else
						{
							signInfoVo.getDayFlags[type - 2] = 1;
						}
						AppData.getInstance().user.signInfoVo.dispatchEvent(new Event(Event.CHANGE));
					}
					else
					{
						Alert.showErrorTip(ErrorTips.instance.getCErrorTip(retCode) + "");
					}
					return true;
				}
				case CMD_Activity.QZONE_AWARD://黄钻奖励
				{
					retCode = buffer.readInt();
					if(retCode!=0)
					{
						Alert.showErrorTip(ErrorTips.instance.getCErrorTip(retCode) + "");
					}
					else
					{
						AppData.getInstance().activityDatemanager.qzoneVo.updateStatus(1);
						Alert.showErrorTip("领取成功");
					}
					return true;
				}
			}
			return false;
		}
		/**
		 * 处理登陆信息
		 * @param mainCmdID
		 * @param subCmdID
		 * @param buffer
		 * @param dataSize
		 * @return 
		 * 
		 */		
		private function onDealLogin(mainCmdID:uint,
									 subCmdID:uint,
									 buffer:ByteArray, 
									 dataSize:int):Boolean
		{
			//交易返回码 0表示成功，非0表示失败1：系统正在维护
			var retCode :int;
			switch(subCmdID)
			{
				case CMD_Login.SUB_Login://登录
				{
					retCode  = buffer.readInt();
					this.sendNotification(Login_Result,retCode);
					return true;
				}
				case CMD_Logic.GUIDE_SETTING://新手设置
				{
					retCode  = buffer.readInt();
					if(retCode != 0)
					{
						Alert.showErrorTip(errorObj[retCode + ""]);
					}
					else
					{
						//获取用户相关信息
						this.sendNotification(ApplicationConstants.Main_Get_User_Base_Info);
					}
					return true;
				}
				case CMD_Logic.GUIDE_NAME_EXSIT://名字验证
				{
					retCode  = buffer.readInt();
					if(retCode != 0)
					{
						Alert.showErrorTip("名字已经被占用，请重新输入!");
					}
					this.sendNotification(CheckUp_Name_Result,retCode);
					return true;
				}
			}
			return false;
		}
		/**
		 *tecent app first request 
		 * 
		 */		
		public function TGWRequest():void
		{
			var tgw_Head :TGW_Head = new TGW_Head();
			tgw_Head.mStr = AppData.getInstance().ip + ":" + AppData.getInstance().port;
			var sendBuf :ByteArray = tgw_Head.toByteArray();
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *登陆请求 
		 * @param userId
		 * @param sessionKey 
		 */		
		public function login(userId :Number,sessionKey :String):void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 4 + 32,CMD_Login.MAIN,CMD_Login.SUB_Login,0);
			sendBuf.writeUnsignedInt(userId);
			StringUtil.writeStringToByteArray(sendBuf,sessionKey,32);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *新手设置 
		 * @param guideSettingVo
		 * 
		 */		
		public function guideSetting(guideSettingVo :GuideSettingVo):void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 15 + 52 + 32,CMD_Logic.MAIN,CMD_Logic.GUIDE_SETTING,guideSettingVo.clubId);
			sendBuf.writeUnsignedInt(guideSettingVo.clubId);
			sendBuf.writeShort(guideSettingVo.teamId);
			sendBuf.writeShort(guideSettingVo.country);
			sendBuf.writeByte(guideSettingVo.place);
			sendBuf.writeShort(10);
			StringUtil.writeStringToByteArray(sendBuf,"1",10);
			sendBuf.writeShort(10);
			StringUtil.writeStringToByteArray(sendBuf,"1",10);
			sendBuf.writeShort(64);
			StringUtil.writeStringToByteArray(sendBuf,guideSettingVo.clubName,64);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *名字验证 
		 * @param cName
		 * 
		 */		
		public function guideCheckName(cName :String):void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 2 + 32,CMD_Logic.MAIN,CMD_Logic.GUIDE_NAME_EXSIT);
			sendBuf.writeShort(32);
			StringUtil.writeStringToByteArray(sendBuf,cName,32);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *获取登录奖励信息 
		 * 
		 */		
		public function getLoginAwardInfo():void
		{
			var variables:URLVariables = ProxyUtils.instance.getUrlVariables();
			variables.method = HttpRequestConst.LOGIN_GET_LOGIN_AWARDINFO;
			ProxyUtils.instance.webClient(getLoginAwardInfoRes,variables,false);
		}
		/**
		 * 获取登录奖励信息  result
		 * @param data
		 * 
		 */		
		private function getLoginAwardInfoRes(data :Object):void
		{
			var str:String = String(data);
			var resultObj :Object;
			try
			{
				resultObj = JSON.decode(str)[0];
			}
			catch(e :Error)
			{
				trace("getLoginAwardInfoRes:",e);
				trace("data:",str);
				return;
			}
			if(resultObj == null)
			{
				trace("",str);
				return;
			}
			if(resultObj.retcode != 0)
			{
				//return;
			}
			var loginAwardVo :LoginAwardVo = new LoginAwardVo();
			loginAwardVo.parseAwardInfo(resultObj);
			AppData.getInstance().user.loginAwardVo = loginAwardVo;
			this.sendNotification(Login_LoginAwardInfo_Result,loginAwardVo);
		}
		/**
		 * 获取登录奖励
		 * 
		 */		
		public function getLoginAward():void
		{
			var variables:URLVariables = ProxyUtils.instance.getUrlVariables();
			variables.method = HttpRequestConst.LOGIN_GET_LOGIN_AWARD;
			ProxyUtils.instance.webClient(getLoginAwardRes,variables,false);
		}
		/**
		 * 获取登录奖励  result
		 * @param data
		 * 
		 */		
		private function getLoginAwardRes(data :Object):void
		{
			var str:String = String(data);
			var resultObj :Object;
			try
			{
				resultObj = JSON.decode(str)[0];
			}
			catch(e :Error)
			{
				trace("getLoginAwardRes:",e);
				trace("data:",str);
				return;
			}
			if(resultObj == null)
			{
				trace("",str);
				return;
			}
			if(resultObj.retcode != 0)
			{
				//Alert.showErrorTip("今天已经领取");
				return;
			}
			/*var loginAwardVo :LoginAwardVo = new LoginAwardVo();
			loginAwardVo.parseAwardInfo(resultObj);*/
			this.sendNotification(Login_GetLoginAward_Result);
		}
		/**
		 *获取签到信息 
		 * 
		 */		
		public function getSignInfo():void
		{
			var variables:URLVariables = ProxyUtils.instance.getUrlVariables();
			variables.method = HttpRequestConst.LOGIN_GET_SIGN_INFO;
			ProxyUtils.instance.webClient(getSignInfoRes,variables,false);
		}
		/**
		 * 获取签到信息   result
		 * @param data
		 * 
		 */		
		private function getSignInfoRes(data :Object):void
		{
			var str:String = String(data);
			var resultObj :Object;
			try
			{
				resultObj = JSON.decode(str)[0];
			}
			catch(e :Error)
			{
				trace("getSignInfoRes:",e);
				trace("data:",str);
				return;
			}
			if(resultObj == null)
			{
				trace("",str);
				return;
			}
			if(resultObj.retcode != 0)
			{
				return;
			}
			var signInfoVo :SignInfoVo = AppData.getInstance().user.signInfoVo;
			signInfoVo.parse(resultObj.signInInfo[0]);
		}
		/**
		 *玩家签到 
		 * 
		 */		
		public function userSign():void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 1,MainCommandType.TASK,CMD_Login.SUB_SIGN,0);
			sendBuf.writeByte(1);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *玩家补签 
		 * 
		 */		
		public function userReSign():void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 1,MainCommandType.TASK,CMD_Login.SUB_SIGN,0);
			sendBuf.writeByte(2);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *获取签到奖励 
		 * @param type
		 * 奖励类型,1：本天领取，2：5天奖励，3：12天奖励，4：26天奖励
		 */		
		public function userGetSignAward(type :int):void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 1,MainCommandType.TASK,CMD_Login.SUB_SIGN_AWARD,0);
			sendBuf.writeByte(type);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *获取黄钻礼包 
		 * 
		 */		
		public function getQzoneVipAward():void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size,MainCommandType.TASK,CMD_Activity.QZONE_AWARD,0);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
	}
}